import { Input, Tree } from "antd";
import { useState, useEffect, useMemo } from "react";
import { listDeptTree, searchDept } from '@/api/system/dept'
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { expandTree } from "@/utils";
import { SvgIcon } from "@/components/icon";
import { useThemeToken } from "@/theme/hooks";
const SelectDeptTree = (props) => {
  const queryClient = useQueryClient()
  const { wantRoot, rootName, onTreeChange } = props
  const [loadedKeys, setLoadedKeys] = useState([])
  const { colorLink } = useThemeToken();
  const [queryParam, setQueryParam] = useState({
    deptName: ''
  });
  const [expandedKeys, setExpandedKeys] = useState([]);
  const { data: treeData, isFetching, refetch } = useQuery({
    queryKey: ['listDeptTree', queryParam],
    initialData: props.treeData,
    queryFn: () => {
      if (queryParam.deptName) {
        return searchDept(queryParam).then((res) => {
          setExpandedKeys(expandTree(res.data || [], 100))
          return res.data || []
        })
      } else {
        return listDeptTree('0', 3).then((res) => {
          setExpandedKeys(expandTree(res.data || [], 3))
          return res.data || []
        })
      }
    },
    staleTime: 0,
  })

  const treeOptions = useMemo(() => {
    if (wantRoot) {
      return [
        {
          id: '-1',
          title: rootName || '根节点',
          children: treeData || [],
          attributes: {
            deptType: 'dept'
          }
        }
      ]
    }
    return treeData
  }, [treeData, wantRoot])

  useEffect(() => {
    if (treeOptions) {
      onTreeChange && onTreeChange([...treeOptions])
    }
  }, [treeOptions])

  const onSearch = (value) => {
    setLoadedKeys([])
    setQueryParam({ deptName: value })
  }

  // 递归查找并更新节点
  const updateTreeNode = (treeData, key, newData) => {
    return treeData.map((node) => {
      if (node.id === key) {
        return { ...node, children: newData || [] };
      }
      if (node.children) {
        return { ...node, children: updateTreeNode(node.children, key, newData) };
      }
      return node;
    });
  };

  const onLoadData = (treeNode) => {
    return listDeptTree(treeNode.id, 1).then(({ data: child = [] }) => {
      if (!loadedKeys.includes(treeNode.id)) {
        setLoadedKeys(val => (val.concat(treeNode.id)))
      }
      const nowTree = updateTreeNode(treeData, treeNode.id, child)
      queryClient.setQueryData(['listDeptTree', queryParam], nowTree)
    })
  }

  return (
    <div>
      {props.showSearch && <Input.Search style={{ paddingBottom: '16px' }} placeholder="输入名称回车查询" onSearch={onSearch} />}
      <Tree
        loadedKeys={loadedKeys}
        selectedKeys={props.selectedKeys}
        expandedKeys={expandedKeys}
        onSelect={props.onSelect}
        autoExpandParent={true}
        fieldNames={{ title: 'title', key: 'id' }}
        treeData={treeOptions}
        loadData={onLoadData}
        onExpand={(expandedKeys) => {
          setExpandedKeys(expandedKeys)
        }}
        titleRender={({ title: text, slots }) => {
          return text
          let icon = 'connections'
          let iconProps = {
            icon: icon,
            size: '20',
            color: colorLink,
            style: {
              marginTop: '-4px', marginRight: '8px'
            }
          }
          if (!slots || !slots.icon) return text
          if (slots.icon === 'org') iconProps.icon = 'companyFill'
          if (slots.icon === 'company') iconProps.icon = 'company'
          if (text.indexOf(queryParam.deptName) > -1) {
            return <><SvgIcon {...iconProps} />
              {text.substr(0, text.indexOf(queryParam.deptName))}
              <span style={{ color: '#f50' }}> {queryParam.deptName} </span>
              {text.substr(text.indexOf(queryParam.deptName) + queryParam.deptName.length)}
            </>
          } else {
            return <><SvgIcon {...iconProps} />{text}</>
          }
        }}
      ></Tree>
    </div>
  );
};

export default SelectDeptTree;